﻿using AgCIM.Tools.DBLink;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Entity.Core.Common.CommandTrees.ExpressionBuilder;
using System.Data.SQLite;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;

namespace MarkDownFileSplitter.Meilisearch
{
    public partial class FormOpenPG : Form
    {
        public DataTable Result { get; private set; }
        public Dictionary<string, string> ColumnType { get; private set; }
        public string TableName { get; private set; }

        private ConnectionDatabase_S2 Connection
        {
            get
            {
                var s2 = AgCIM.Tools.DBLink.ConnectionDatabase_S2.BuildPGConnection(this.txtAddress.Text, this.textBox_port.Text,
               this.txtDatabase.Text, this.txtUsername.Text, this.txtPassword.Text);
                return s2;
            }
        }

        public FormOpenPG()
        {
            InitializeComponent();
        }

        private void FormOpenPG_Load(object sender, EventArgs e)
        {
            LoadTmpFile();
        }

        private List<string> m_allTables = new List<string>();
        private void button1_Click(object sender, EventArgs e)
        {
            this.comboBoxTableName.Items.Clear();
            this.cbb_batchField.Items.Clear();
            var s2 = Connection;
            s2.GetTableNames().ForEach(x => { 
                this.comboBoxTableName.Items.Add(x); 
                m_allTables.Add(x);
                this.cbb_batchField.Items.Add(x);
            });
            s2.Dispose();

            this.cbb_batchField.SelectedText = "batchkey";
            cbb_batchField_SelectedValueChanged(null, null);
        }

        private void SaveInputToTmpFile()
        {
            // 获取程序运行目录
            string appPath = AppDomain.CurrentDomain.BaseDirectory;
            // 拼接tmp目录路径
            string tmpPath = System.IO.Path.Combine(appPath, "tmp");
            // 确保tmp目录存在
            if (!System.IO.Directory.Exists(tmpPath))
            {
                System.IO.Directory.CreateDirectory(tmpPath);
            }
            // 拼接FormOpenPG.input文件路径
            string filePath = System.IO.Path.Combine(tmpPath, "FormOpenPG.input");
            // 准备要写入的内容
            string content = $"{this.txtAddress.Text},{this.textBox_port.Text},{this.txtDatabase.Text},{this.txtUsername.Text},{this.txtPassword.Text},{this.comboBoxTableName.Text}";
            // 将内容写入文件
            System.IO.File.WriteAllText(filePath, content);
        }

        private void LoadTmpFile()
        {
            // 获取程序运行目录
            string appPath = AppDomain.CurrentDomain.BaseDirectory;
            // 拼接tmp目录路径
            string tmpPath = System.IO.Path.Combine(appPath, "tmp");
            // 拼接FormOpenPG.input文件路径
            string filePath = System.IO.Path.Combine(tmpPath, "FormOpenPG.input");

            // 检查文件是否存在
            if (System.IO.File.Exists(filePath))
            {
                // 读取文件内容
                string content = System.IO.File.ReadAllText(filePath);
                // 分割内容
                string[] parts = content.Split(',');

                if (parts.Length >= 5)
                {
                    this.txtAddress.Text = parts[0];
                    this.textBox_port.Text = parts[1];
                    this.txtDatabase.Text = parts[2];
                    this.txtUsername.Text = parts[3];
                    this.txtPassword.Text = parts[4];
                }
                if (parts.Length >= 6)
                {
                    this.comboBoxTableName.Text = parts[5];
                }
            }

        }

        private void button2_Click(object sender, EventArgs e)
        {
            var s2 = Connection;
            if (this.cbb_batchField.Text != "" && this.cbb_batchValue.Text != "")
            {
                string sql = $@" SELECT *  FROM ""{this.comboBoxTableName.Text}""  WHERE ""{this.cbb_batchField.Text}"" = '{this.cbb_batchValue.Text}' ";
                Result = s2.SelectData(sql);
            }
            else
                Result = s2.SelectData("select * from " + this.comboBoxTableName.Text);

            ConvertToTuoFeng();
            var ColumnTypeDT = s2.SelectData("SELECT column_name, data_type FROM information_schema.columns WHERE table_name = '" + this.comboBoxTableName.Text + "'");
            ColumnType = new Dictionary<string, string>();
            foreach (DataRow item in ColumnTypeDT.Rows)
            {
                var str = ConvertToTuoFeng(item.ItemArray[0].ToString());
                ColumnType.Add(str.ToLower(), item.ItemArray[1].ToString().ToLower());
            }

            s2.Dispose();

            this.DialogResult = DialogResult.OK;
            this.Close();

            SaveInputToTmpFile();
        }

        #region 转驼峰
        private void ConvertToTuoFeng()
        {
            for (var i = 0; i < Result.Columns.Count; i++)
            {
                var cname = ConvertToTuoFeng(Result.Columns[i].ColumnName);
                Result.Columns[i].ColumnName = cname;
            }
        }
        private string ConvertToTuoFeng(string cname)
        {
            while (cname.IndexOf("_") >= 0)
            {
                var t = cname.IndexOf("_");
                if (cname.Length == t + 1)
                {
                    break;
                }
                else
                {
                    cname = cname.Substring(0, t) + (cname[t + 1] + "").ToUpper() + cname.Substring(t + 2);
                }
            }
            return cname;
        }
        #endregion

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBox1.Text))
            {
                this.comboBoxTableName.Items.Clear();
                this.comboBoxTableName.Items.AddRange(m_allTables.ToArray());
                return;
            }
            var newItems = new List<string>();
            for (var i = 0; i < m_allTables.Count; i++)
            {
                if (m_allTables[i].IndexOf(this.textBox1.Text, StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    newItems.Add(m_allTables[i]);
                }
            }
            this.comboBoxTableName.Items.Clear();
            this.comboBoxTableName.Items.AddRange(newItems.ToArray());
        }

        private void comboBoxTableName_SelectedValueChanged(object sender, EventArgs e)
        {
            List<string> m_allFieldss = new List<string>();
            var s2 = Connection;
            s2.GetRowNames(comboBoxTableName.Text).ForEach(x => { this.comboBoxTableName.Items.Add(x); m_allFieldss.Add(x); });
            s2.Dispose();
            this.cbb_batchField.Items.Clear();
            this.cbb_batchField.Items.AddRange(m_allFieldss.ToArray());
        }

        private void cbb_batchField_SelectedValueChanged(object sender, EventArgs e)
        {
            List<string> m_alldistinctValue = new List<string>();

            string tableName = this.comboBoxTableName.Text;
            string columnName = this.cbb_batchField.Text;
            string sortDirection = "ASC";

            string sql = @" SELECT DISTINCT ""{0}"" FROM ""{1}"" ORDER BY ""{0}"" {2}; ";
            string formattedSql = string.Format(sql, columnName, tableName, sortDirection);
            var s2 = Connection;
            var values = s2.SelectData(formattedSql);
            s2.Dispose();

            foreach (System.Data.DataRow item in values.Rows)
            {
                m_alldistinctValue.Add(item.ItemArray[0].ToString());
            }

            this.cbb_batchValue.Items.Clear();
            this.cbb_batchValue.Items.AddRange(m_alldistinctValue.ToArray());
        }
    }
}
